<template>
  <!-- 此处的 touchstart 事件：点其他地方关闭键盘，解决挡住滑动选择问题 -->
  <div class="create-lectures" @touchstart="$event.target.type!=='text'&&($refs.eIptText.blur(),$refs.eIptTextPlace.blur())">
    <!-- <VHeader :title="bus.title"></VHeader> -->
    <div class="c-main">
      <div class="c-item-name">
        <div class="c-ipt-b">
          <input ref="eIptText" class="c-ipt" :class="{err:errorCourseName}" type="text" placeholder="请输入课程名称" v-model.trim="courseName" @input="errorCourseName=false">
        </div>
      </div>
      <div class="c-item" v-click="selectSubject">
        <span class="c-lb">选择科目</span>
        <span v-if="selectedSubject===null" class="c-tip" :class="{err:errorSubject}">请选择科目
          <i class="iconfont"></i>
        </span>
        <span class="c-value">{{selectedSubject&&selectedSubject.subject_name}}</span>
      </div>
      <div class="c-item" v-click="selectObj">
        <span class="c-lb">授课对象</span>
        <span class="c-tip" :class="{err:errorObj}" v-if="selectedObj===null">请选择授课对象
          <i class="iconfont"></i>
        </span>
        <span class="c-value">{{selectedObj&&(selectedObj.grade_name+selectedObj.class_name)}}</span>
      </div>
      <div class="c-item" v-click="selectTime">
        <span class="c-lb">授课时间</span>
        <span class="c-tip" :class="{err:errorDate}" v-if="selectedDateTimeSubmit===null">请设置授课时间
          <i class="iconfont"></i>
        </span>
        <span class="c-value">{{selectedDateTimeSubmit}}</span>
      </div>
      <!-- <div class="c-item" v-click="selectPlace">
        <span class="c-lb">授课地点</span>
        <span class="c-tip" :class="{err:errorPlace}" v-if="selectedPlace===null">请选择授课地点<i class="iconfont"></i></span>
        <span class="c-value">{{selectedPlace&&selectedPlace.class_room_name}}</span>
      </div> -->
      <div class="c-item-place">
        <div class="iconfont c-place-select-btn" v-click="selectPlace">&#xe607;</div>
        <div class="c-ipt-b">
          <input ref="eIptTextPlace" class="c-ipt" :class="{err:errorPlace}" type="text" placeholder="请输入授课地点" @input="errorPlace=false;placeText=$event.target.value;selectedPlace=null" :value="placeText">
        </div>
      </div>
      <div class="c-item" v-click="selectGroup">
        <span class="c-lb">所属科组</span>
        <span class="c-tip" :class="{err:errorGroup}" v-if="selectedGroup===null">请选择科组
          <i class="iconfont"></i>
        </span>
        <span class="c-value">{{selectedGroup&&selectedGroup.subject_group_name}}</span>
      </div>
      <div class="c-btn">
        <BaseButtonFull v-click="submit">提交</BaseButtonFull>
      </div>
    </div>
    <SelectBottom ref="vSelectBottom" />
    <MessageRemind ref="vMessageRemind" />
    <SlideSelect ref="vSlideSelect" />
    <DateSelect ref="vDateSelect" />
    <!-- <SlideSelectDateDemo/> -->
  </div>
</template>

<script>
// import VHeader from '@/components/VHeader'
import BaseButtonFull from '@/components/BaseButtonFull'
import SelectBottom from '@/components/SelectBottom'
import MessageRemind from '@/components/MessageRemind'
import SlideSelect from '@/modules/slide-select2/SlideSelect'
import DateSelect from '../DateSelect'
// import SlideSelectDateDemo from '@/modules/slide-select-date/SlideSelectDateDemo'
function numfill (number) {
  if (number < 10) {
    return '0' + number
  }
  return number
}
export default {
  data () {
    return {
      courseName: '',

      selectedSubject: null,
      selectedObj: null,
      selectedObjIndexs: null,
      selectedDate: null,
      selectedPlace: null,
      selectedGroup: null,

      errorCourseName: false,
      errorSubject: false,
      errorObj: false,
      errorDate: false,
      errorPlace: false,
      errorGroup: false,

      // 地点特殊处理。输入定制
      placeText: '',

      // 编辑基础数据
      dataEdit: {}
    }
  },
  beforeRouteEnter (to, from, next) {
    // 没数据情况进行重定向
    if (to.name === 'EditLectures') { // 编辑情况
      if (to.params.id === undefined) {
        next({ name: 'LecturesManage' })
        return
      }
    }
    next()
  },
  mounted () {
    if (this.$route.name === 'EditLectures') { // 编辑情况
      this.bus.title = '开课编辑'
      let dataEdit = this.dataEdit = this.$route.params
      this.courseName = dataEdit.name.trim().replace(/[《》]/g, '')
      this.selectedSubject = {
        subject_id: dataEdit.subject_id,
        subject_name: dataEdit.subject_name
      }
      this.selectedObj = {
        grade_id: dataEdit.grade_id,
        grade_name: dataEdit.grade_name,
        class_id: dataEdit.class_id,
        class_name: dataEdit.class_name
      }

      let selectedDate = this.selectedDate = []
      dataEdit.lesson_date.split('T')[0].match(/\d+/g).concat(dataEdit.start_time.split(':')).forEach((v, i) => {
        if (v && i !== 5) {
          v *= 1
          selectedDate.push({
            value: v
          })
        }
      })

      let roomId = dataEdit.class_room_id
      let placeText = this.placeText = dataEdit.class_room_name
      if (roomId) {
        this.selectedPlace = {
          class_room_id: roomId,
          class_room_name: placeText
        }
      }

      this.selectedGroup = {
        subject_group_id: dataEdit.group_id,
        subject_group_name: dataEdit.group_name
      }
    } else {
      // 弃用 科组只有一个情况初始选择
      // this.getCacheData('subjectGroups').then(data => {
      //   if (data) {
      //     let groups = data.subject_groups
      //     if (groups.length === 1) {
      //       this.selectedGroup = groups[0]
      //     }
      //   }
      // })

      // 科目，对象，科组，初始选中第一个，地点等于对象
      this.getCampusinfo().then(data => {
        if (data) {
          this.selectedSubject = data.subjects[0] || null
          this.selectedObj = data.schoolClasses[0] || null
        }
      }).then(() => {
        // 有授课班级则使用授课班级
        this.ajaxGet('/lecture/v1/teacherClasses').then(data => {
          if (data) {
            data = data.data[0] || {}
            let cla = data.class
            if (cla) {
              cla.class_id = cla.id
              cla.class_name = cla.alias
              this.selectedObj = cla
            }
          }
        })
      })

      this.getCacheData('subjectGroups').then(data => {
        if (data) {
          this.selectedGroup = data.subject_groups[0] || null
        }
      })
    }
  },
  computed: {
    selectedDateTimeSubmit () {
      let { selectedDateSubmit, selectedTimeSubmit } = this
      if (selectedDateSubmit) {
        return `${selectedDateSubmit} ${selectedTimeSubmit}`
      }
      return null
    },
    selectedDateSubmit () {
      let date = this.selectedDate
      if (date && date.length) {
        return `${date[0].value}-${numfill(date[1].value)}-${numfill(date[2].value)}`
      }
      return null
    },
    selectedTimeSubmit () {
      let date = this.selectedDate
      if (date && date.length) {
        return `${numfill(date[3].value)}:${numfill(date[4].value)}`
      }
      return null
    },
    // 编辑情况 course_id。可用来判断编辑状态
    isEdit () {
      return this.dataEdit.id
    }
  },
  watch: {
    // 对象同步地点
    selectedObj (selectedObj) {
      let {grade_name: g, class_name: c} = selectedObj
      let regPlace = new RegExp(g + '\\s*' + c)
      this.placeText = g + c
      // 查询是否有对应地点id，没有则为空
      this.selectedPlace = null
      this.getCacheData('classrooms').then(data => {
        if (data) {
          data.classrooms.forEach(item => {
            if (regPlace.test(item.class_room_name)) {
              this.selectedPlace = item
            }
          })
        }
      })
    }
  },
  methods: {
    submit () {
      let { courseName, selectedSubject, selectedObj, selectedDate, selectedDateSubmit, selectedTimeSubmit, selectedPlace, selectedGroup, placeText } = this
      let { vMessageRemind } = this.$refs
      placeText = placeText.trim()
      // c.log({
      //   course_id: this.dataEdit.id, // 编辑情况。值为 undefined 会自动忽略此参数
      //   course_name: courseName, // 公开课名称
      //   subject_id: selectedSubject.subject_id, // 科目ID
      //   grade_id: selectedObj.grade_id, // 年级ID
      //   class_id: selectedObj.class_id, // 班级ID
      //   lesson_date: selectedDateSubmit, // 开课日期
      //   start_time: selectedTimeSubmit + ':00', // 开课时间
      //   class_room_id: selectedPlace && selectedPlace.class_room_id, // 教室ID
      //   class_room_name: placeText, // 教室名（上课地点）
      //   subject_group_id: selectedGroup.subject_group_id // 科组ID
      // })
      let err = false
      if (courseName.length === 0) {
        err = this.errorCourseName = true
      }
      if (selectedSubject === null) {
        err = this.errorSubject = true
      }
      if (selectedObj === null) {
        err = this.errorObj = true
      }
      if (selectedDate === null) {
        err = this.errorDate = true
      } else {
        // 不能低于今天
        let sDate = new Date(selectedDate[0].value, selectedDate[1].value - 1, selectedDate[2].value, selectedDate[3].value, selectedDate[4].value)
        if (sDate < (new Date())) {
          err = this.errorDate = true
          this.selectedDate = null
          this.$toast.error('提交失败，授课时间不能低于今天')
        }
      }
      if (selectedPlace === null && placeText.length === 0) {
        err = this.errorPlace = true
      }
      if (!selectedGroup) {
        err = this.errorGroup = true
      }
      if (err) return

      this.$loading.show()
      this.$axios.post(`/lecture/v1/${this.isEdit ? 'editOpenCourse' : 'requestOpenCourse'}`, {
        course_id: this.dataEdit.id, // 编辑情况。值为 undefined 会自动忽略此参数
        course_name: '《' + courseName + '》', // 公开课名称
        subject_id: selectedSubject.subject_id, // 科目ID
        grade_id: selectedObj.grade_id, // 年级ID
        class_id: selectedObj.class_id, // 班级ID
        lesson_date: selectedDateSubmit, // 开课日期
        start_time: selectedTimeSubmit + ':00', // 开课时间
        class_room_id: selectedPlace ? selectedPlace.class_room_id : undefined, // 教室ID
        class_room_name: placeText, // 教室名（上课地点）
        subject_group_id: selectedGroup.subject_group_id // 科组ID
      }).then(({ data }) => {
        if (data.status !== 200) {
          this.$toast.error('服务器异常')
          return
        }
        let { result } = data
        if (result.success) {
          this.$toast.success('申请开课成功')
          this.$router.push({
            name: 'LecturesManage'
          })
        } else {
          let { rocc } = result
          switch (result.type) {
            case 0:
              this.$toast.error('开课时间已过')
              break
            case 1:
              vMessageRemind.show({
                text: `非常抱歉，【${rocc.lesson_date}${rocc.lesson_name}】，【${rocc.teacher_name}】已预订了【${rocc.class_room_name}】，如您需要可以直接联系管理员`
              })
              break
            case 2:
              vMessageRemind.show({
                text: `非常抱歉，【${rocc.lesson_date}${rocc.lesson_name}】，【${rocc.teacher_name}】老师已预订了【${rocc.class_room_name}】，如您需要可以直接联系管理员`
              })
              break
            case 3:
              this.$toast.error('后台异常')
              break
            default:
              this.$toast.error('失败，如您需要可以直接联系管理员')
          }
        }
      }).catch(e => { this.$toast.error(e.message) }).then(() => {
        this.$loading.hide()
      })
    },
    getCampusinfo () {
      if (this.campusinfoData) {
        return new Promise((resolve, reject) => {
          resolve(this.campusinfoData)
        })
      } else {
        this.$loading.show()
        return this.$axios.get('/lecture/v1/campusinfo').then(({ data }) => {
          if (data.status === 200) {
            return (this.campusinfoData = data.result)
          } else {
            this.$toast.error(data.message)
          }
        }).catch(e => { this.$toast.error(e.message) }).then(d => {
          this.$loading.hide()
          return d
        })
      }
    },
    // 通用 ajax
    ajaxGet (url, config) {
      this.$loading.show()
      return this.$axios.get(url, config).then(({ data }) => {
        if (data.status === 200) {
          return (data.result)
        } else {
          this.$toast.error(data.message)
        }
      }).catch(e => { this.$toast.error(e.message) }).then(d => {
        this.$loading.hide()
        return d
      })
    },
    // 取数据缓存
    getCacheData (name, config) {
      let nameData = name + 'Data'
      if (this[nameData]) {
        return new Promise((resolve, reject) => {
          resolve(this[nameData])
        })
      } else {
        return this.ajaxGet('/lecture/v1/' + name, config).then(data => {
          if (data) {
            return (this[nameData] = data)
          }
        })
      }
    },
    selectSubject () {
      let { vSelectBottom } = this.$refs
      vSelectBottom.show()
      this.getCampusinfo().then(data => {
        if (data) {
          let selectedSubject = this.selectedSubject
          vSelectBottom.setOptions({
            idKey: 'subject_id',
            nameKey: 'subject_name',
            list: data.subjects,
            selectedId: selectedSubject && selectedSubject.subject_id,
            onConfirm: (selectedData) => {
              this.selectedSubject = selectedData
            }
          })
        }
      })
    },
    selectObj () {
      let that = this
      let { vSlideSelect } = this.$refs
      vSlideSelect.show()
      this.getCampusinfo().then(data => {
        if (data) {
          let dataDict = {}
          let gradeListData = []
          data.schoolClasses.forEach(d => {
            if (d.grade_name === '已毕业') return
            let gradeId = d.grade_id
            let gradeName = d.grade_name
            let list = dataDict[gradeId]
            if (list === undefined) {
              list = dataDict[gradeId] = []
              gradeListData.push({
                value: gradeId,
                text: gradeName
              })
            }
            list.push(d)
          })
          // 排序
          this.gradSort(gradeListData)
          // 根据已选项初始列表数据
          let classListData = []
          let { selectedObj } = this
          let selectedValues
          if (selectedObj && dataDict[selectedObj.grade_id]) { // dataDict[selectedObj.grade_id] 兼容为空情况
            classListData = that.getClassListData(dataDict[selectedObj.grade_id])
            selectedValues = [selectedObj.grade_id, selectedObj.class_id]
          } else {
            classListData = that.getClassListData(dataDict[gradeListData[0].value])
          }
          vSlideSelect.setOptions({
            lists: [gradeListData, classListData],
            // selectedIndexs: selectedObjIndexs, // 指定选择
            selectedValues,
            onChange (index, id) {
              if (id === 0) {
                this.setList(1, that.getClassListData(dataDict[gradeListData[index].value]))
              }
            },
            onConfirm: vm => {
              let indexs = vm.getSelectedIndexs()
              this.selectedObjIndexs = indexs
              let classes = dataDict[gradeListData[indexs[0]].value]
              this.selectedObj = classes[indexs[1]]
            }
          })
        }
      })
    },
    selectTime () {
      this.$refs.vDateSelect.show({
        selectedValuesObj: this.selectedDate,
        onConfirm: (vm) => {
          this.selectedDate = vm.getSelectedValues()
        }
      })
    },
    selectPlace () {
      let { vSlideSelect } = this.$refs
      vSlideSelect.show()
      this.getCacheData('classrooms').then(data => {
        if (data) {
          let list = []
          let { classrooms } = data
          classrooms.forEach(item => {
            list.push({
              value: item.class_room_id,
              text: item.class_room_name
            })
          })
          vSlideSelect.setOptions({
            selectedValues: [this.selectedPlace && this.selectedPlace.class_room_id],
            lists: [list],
            onConfirm: vm => {
              let selectedPlace = this.selectedPlace = classrooms[vm.getSelectedIndexs()[0]]
              this.placeText = selectedPlace.class_room_name
            }
          })
        }
      })
    },
    selectGroup () {
      let { vSelectBottom } = this.$refs
      vSelectBottom.show()
      this.getCacheData('subjectGroups', {
        params: {
          user_id: this.dataEdit.user_id // 编辑情况。undefined 自动忽略此值
        }
      }).then(data => {
        if (data) {
          let selectedGroup = this.selectedGroup
          vSelectBottom.setOptions({
            idKey: 'subject_group_id',
            nameKey: 'subject_group_name',
            list: data.subject_groups,
            selectedId: selectedGroup && selectedGroup.subject_group_id,
            onConfirm: (selectedData) => {
              this.selectedGroup = selectedData
            }
          })
        }
      })
    },
    gradSort (gradeListData) {
      let gradKey = {
        '一年级': '1001',
        '二年级': '1002',
        '三年级': '1003',
        '四年级': '1004',
        '五年级': '1005',
        '六年级': '1006',
        '七年级': '1007',
        '八年级': '1008',
        '九年级': '1009',
        '高一': '1020',
        '高二': '1021',
        '高三': '1022',
        '已毕业': '1022'
      }
      gradeListData.sort(function (v1, v2) {
        v1 = gradKey[v1.text]
        v2 = gradKey[v2.text]
        if (v1 > v2) return 1
        if (v1 < v2) return -1
        return 0// 不处理
      })
    },
    getClassListData (list) {
      // 排序 list
      list.sort(function (v1, v2) {
        let n1 = v1.class_name
        let n2 = v2.class_name
        v1 = parseFloat(n1)
        v2 = parseFloat(n2)
        let isNaN1 = isNaN(v1)
        let isNaN2 = isNaN(v2)
        if (isNaN1) {
          if (isNaN2) {
            if (n1 > n2) return 1
            if (n1 < n2) return -1
            return 0
          }
          return 1
        } else {
          if (isNaN2) {
            return -1
          }
          if (v1 > v2) return 1
          if (v1 < v2) return -1
          return 0
        }
      })

      let selectListData = []
      list.forEach(d => {
        selectListData.push({
          value: d.class_id,
          text: d.class_name
        })
      })
      return selectListData
    }
  },
  components: {
    // VHeader,
    BaseButtonFull,
    SelectBottom,
    MessageRemind,
    // SlideSelectDateDemo,
    SlideSelect,
    DateSelect
  }
}
</script>

<style scoped>
.create-lectures {
}
.c-main {
  /* margin-top: 38px; */
}
.c-item {
  height: 50px;
  background-color: #fff;
  margin-bottom: 14px;
  box-sizing: border-box;

  padding: 12px 14px;
  &:active {
    background-color: #ccc;
  }
  .c-lb {
    display: inline-block;
    font-size: 16px;
    padding: 2px 0;
    color: #666;
  }
  .c-tip {
    float: right;
    color: #bbb;
    font-size: 15px;
    margin-top: 2px;

    &.err {
      color: red;
    }
    .iconfont:after {
      content: "\e606";
      display: inline-block;
      transform: rotate(180deg);
      margin-left: 6px;
    }
  }
  .c-value {
    float: right;
    margin-top: 4px;
  }
}
.c-item-name {
  height: 60px;
  background-color: #fff;
  margin-bottom: 14px;
  /* box-sizing: border-box; */
  /* padding: 20px 15px; */

  .c-ipt-b {
  }
  .c-ipt {
    font-size: 16px;
    width: 100%;
    border: 0;
    outline: none;
    padding: 20px 15px;
    box-sizing: border-box;
    &::placeholder {
      color: #bbb;
    }
    &.err::placeholder {
      color: red;
    }
  }
}
.c-item-place {
  height: 50px;
  background-color: #fff;
  margin-bottom: 14px;
  /* box-sizing: border-box; */
  /* padding: 20px 15px; */
  .c-place-select-btn {
    float: right;
    width: 50px;
    height: 50px;
    font-size: 32px;
    box-sizing: border-box;
    color: #bbb;
    border-left: 1px solid #ddd;
    text-align: center;
    line-height: 1.6;
  }
  .c-ipt-b {
    overflow: hidden;
  }
  .c-ipt {
    font-size: 16px;
    width: 100%;
    border: 0;
    outline: none;
    padding: 16px 15px;
    box-sizing: border-box;
    &::placeholder {
      color: #bbb;
    }
    &.err::placeholder {
      color: red;
    }
  }
}
.c-btn {
  margin: 0 15px;
  padding: 18px 0;
}
</style>
